﻿using Microsoft.Extensions.Configuration;
using OConf.Common;
using OConf.Entity;
using OConf.IBLL;
using OConf.Model;
using OConf.Model.Common;
using OConf.Model.RequestInput.ConfigInfo;
using OConf.Service;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace OConf.BLL
{
    public class ConfigInfoBLL: IConfigInfoBLL
    {
        private readonly IConfiguration _configuration;
        private readonly ConfigInfoService _configInfoService;
        private readonly CNameSpaceService _cNameSpaceService;
        private readonly ProjectInfoService _projectInfoService;

        public ConfigInfoBLL(IConfiguration configuration)
        {
            _configuration = configuration;
            _configInfoService = new ConfigInfoService(_configuration);
            _cNameSpaceService = new CNameSpaceService(_configuration);
            _projectInfoService = new ProjectInfoService(_configuration);
        }

        /// <summary>
        /// 新增配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> AddConfigInfo(AddConfigInfoInput input)
        {
            try
            {
                //同一个项目，同一个命名空间下配置信息Key不能重复
                if (_configInfoService.IsExistsByKey(input.ConfigKey, input.ProjectID, input.NameSpaceID))
                {
                    return ReturnDataHelper<bool>.Success("Key值已存在", false);
                }

                CNameSpaceEntity cNameSpace = _cNameSpaceService.FindEntity(input.NameSpaceID);

                if (cNameSpace == null)
                {
                    return ReturnDataHelper<bool>.NoExists("NameSpace信息不存在", false);
                }

                ConfigInfoEntity configInfoEntity = new ConfigInfoEntity()
                {
                    ID = Guid.NewGuid().ToString(),
                    ProjectID = input.ProjectID,
                    ConfigKey = input.ConfigKey,
                    ConfigValue = input.ConfigValue,
                    ConfigDescription = input.ConfigDescription,
                    NameSpaceID = input.NameSpaceID,
                    State = (int)ConfigInfoState.增,
                    CreateTime = DateTime.Now
                };

                _configInfoService.AddEntity(configInfoEntity);

                //NameSpace设置为未发布
                if (cNameSpace.IsPublish)
                {
                    cNameSpace.IsPublish = false;
                    _cNameSpaceService.Update(cNameSpace);
                }

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("AddConfigInfo,新增配置信息", ex);
                return ReturnDataHelper<bool>.Fail("系统异常", false);
            }
        }

        /// <summary>
        /// 编辑配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> EditConfigInfo(EditConfigInfoInput input)
        {
            try
            {
                ConfigInfoEntity configInfo = _configInfoService.FindEntity(input.ID);
                if (configInfo == null)
                {
                    return ReturnDataHelper<bool>.NoExists("配置信息不存在", false);
                }

                if (!_cNameSpaceService.IsExist(input.NameSpaceID))
                {
                    return ReturnDataHelper<bool>.NoExists("NameSpace信息不存在", false);
                }

                //配置信息没有改变
                if (configInfo.ConfigValue == input.ConfigValue && configInfo.ConfigDescription == input.ConfigDescription)
                {
                    return ReturnDataHelper<bool>.Success("操作成功", true);
                }

                //只有Value发生变化时才需要重新发布
                if (configInfo.ConfigValue != input.ConfigValue)
                {
                    configInfo.ConfigValue = input.ConfigValue;
                    configInfo.ConfigDescription = input.ConfigDescription;

                    //配置信息为“已发布”和“删”状态时，修改配置信息后状态更新为“改”
                    //配置信息为“增”和“改”时，配置信息状态不变
                    if (configInfo.State == (int)ConfigInfoState.已发布 || configInfo.State == (int)ConfigInfoState.删)
                    {
                        configInfo.State = (int)ConfigInfoState.改;
                    }

                    _configInfoService.UpdateEntity(configInfo);

                    //NameSpace设置为未发布
                    _cNameSpaceService.UpdateIsPublish(input.NameSpaceID, false);
                }
                else if (configInfo.ConfigDescription != input.ConfigDescription)
                {
                    _configInfoService.UpdateDescription(input.ID, input.ConfigDescription);
                }

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("EditConfigInfo,编辑配置信息", ex);
                return ReturnDataHelper<bool>.Fail("系统异常", false);
            }
        }

        /// <summary>
        /// 删除配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> DeleteConfigInfo(DeleteConfigInfoInput input)
        {
            try
            {
                ConfigInfoEntity entity = _configInfoService.FindEntity(input.ID);
                if (entity == null)
                {
                    return ReturnDataHelper<bool>.NoExists("配置信息不存在", false);
                }

                CNameSpaceEntity cNameSpace = _cNameSpaceService.FindEntity(entity.NameSpaceID);
                if (cNameSpace == null)
                {
                    return ReturnDataHelper<bool>.NoExists("NameSpace信息不存在", false);
                }

                if (entity.State == (int)ConfigInfoState.已发布 || entity.State == (int)ConfigInfoState.改)
                {
                    _configInfoService.UpdateState(input.ID, ConfigInfoState.删);

                    //NameSpace设置为未发布
                    if (cNameSpace.IsPublish)
                    {
                        _cNameSpaceService.UpdateIsPublish(cNameSpace.ID, false);
                    }
                }
                else if (entity.State == (int)ConfigInfoState.增)
                {
                    _configInfoService.Delete(input.ID);

                    //命名空间下配置信息状态都为“已发布”时，更新命名空间为已发布
                    if (_configInfoService.IsPublishAll(cNameSpace.ID))
                    {
                        _cNameSpaceService.UpdateIsPublish(cNameSpace.ID, true);
                    }
                }
                else
                {
                    return ReturnDataHelper<bool>.Fail("该配置不允许删除", false);
                }
                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("DeleteConfigInfo,删除配置信息", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 还原配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<bool> RestoreConfigInfo(RestoreConfigInfoInput input)
        {
            try
            {
                ConfigInfoEntity entity = _configInfoService.FindEntity(input.ID);
                if (entity == null)
                {
                    return ReturnDataHelper<bool>.NoExists("配置信息不存在", false);
                }

                if (entity.State != (int)ConfigInfoState.删)
                {
                    return ReturnDataHelper<bool>.Fail("该配置不满足还原条件", false);
                }

                _configInfoService.UpdateState(input.ID, ConfigInfoState.已发布);

                //命名空间下配置信息状态都为“已发布”时，更新命名空间为已发布
                if (_configInfoService.IsPublishAll(entity.NameSpaceID))
                {
                    _cNameSpaceService.UpdateIsPublish(entity.NameSpaceID, true);
                }

                return ReturnDataHelper<bool>.Success("操作成功", true);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("RestoreConfigInfo,还原配置信息", ex);
                return ReturnDataHelper<bool>.Exception("系统异常", false);
            }
        }

        /// <summary>
        /// 根据NameSpaceID获取配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<List<ConfigInfoModel>> GetConfigInfoByNameSpaceID(GetConfigInfoListInput input)
        {
            try
            {
                List<ConfigInfoEntity> list = _configInfoService.GetConfigInfoByNameSpaceID(input.NameSpaceID);
                List<ConfigInfoModel> models = list.Select(w => new ConfigInfoModel()
                {
                    ID = w.ID,
                    ProjectID = w.ProjectID,
                    ConfigKey = w.ConfigKey,
                    ConfigValue = w.ConfigValue,
                    ConfigDescription = w.ConfigDescription,
                    CreateTime = w.CreateTime,
                    NameSpaceID = w.NameSpaceID,
                    State = w.State,
                }).ToList();

                return ReturnDataHelper<List<ConfigInfoModel>>.Success("操作成功", models);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("GetConfigInfoByNameSpaceID,根据NameSpaceID获取配置信息", ex);
                return ReturnDataHelper<List<ConfigInfoModel>>.Exception("系统异常", null);
            }
        }

        /// <summary>
        /// 获取配置文件信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ReturnData<List<ConfigFileInfo>> GetConfigFileInfo(GetConfigFileInfoInput input)
        {
            try
            {
                ProjectInfoEntity projectInfo = _projectInfoService.FindEnity(input.ProjectID);
                if (projectInfo == null)
                {
                    return ReturnDataHelper<List<ConfigFileInfo>>.NoExists("项目信息不存在", null);
                }

                //将配置信息保存到json文件中
                string fileDirPath = Path.Combine(GlobalValues.ConfigFileSaveDirPath, projectInfo.ProjectName);

                List<ConfigFileInfo> qCFileInfos = GetFileInfo(fileDirPath);

                return ReturnDataHelper<List<ConfigFileInfo>>.Success("操作成功", qCFileInfos);
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("GetConfigFileInfo,获取配置文件信息", ex);
                return ReturnDataHelper<List<ConfigFileInfo>>.Exception("系统异常", null);
            }
        }

        private List<ConfigFileInfo> GetFileInfo(string desDir)
        {
            try
            {
                if (!Directory.Exists(desDir))
                {
                    return new List<ConfigFileInfo>();
                }

                DirectoryInfo directoryInfo = new DirectoryInfo(desDir);
                return (from w in directoryInfo.GetFiles()
                        select new ConfigFileInfo
                        {
                            FileName = w.Name,
                            CreateTime = w.CreationTime,
                            ModifyTime = w.LastWriteTime,
                            ExFileName = w.Extension
                        }).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
